<template>
  <div
    id="notificationContainer"
    class="flex justify-center fixed top-0 left-0 right-0 bottom-0 items-center z-30 bg-black bg-opacity-80"
  >
    <div
      class="flex flex-col items-center notification content bg-gray-800 text-gray-100 rounded relative z-50 max-w-sm mx-4 p-2"
    >
      <div class="mb-2 max-w-sm max-h-80">
        <img ref="image" :src="src" />
      </div>
      <div class="flex">
        <button
          class="p-3 font-extrabold rounded tracking-wide focus:outline-none select-none bg-gray-700 mr-2 hover:bg-gray-600 focus:bg-gray-600 transition-colors duration-200"
          @click="$emit('closeCropper')"
        >
          Cancel
        </button>
        <button
          class="font-extrabold leading-none tracking-wide select-none shrink-0 p-3 text-white bg-emerald-600 rounded hover:bg-emerald-500 focus:bg-emerald-500 transition-colors duration-200 focus:outline-none"
          @click="cropPhoto"
        >
          Crop photo
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import Cropper from 'cropperjs'
import 'cropperjs/dist/cropper.css'
import axios from 'axios'
import { uploadConfig } from '~/services/api.config'
export default {
  props: ['src', 'mime', 'content', 'resizeImage', 'type'],
  data() {
    return {
      cropper: {},
      dataURL: null,
      blobData: null,
      image: {},
    }
  },
  methods: {
    async cropPhoto() {
      let vm = this
      const canvas = this.cropper.getCroppedCanvas()

      try {
        // 将 canvas 转换为 blob
        const blob = await new Promise((resolve) => {
          canvas.toBlob(resolve, this.mime, 0.8)
        })

        // 创建文件对象
        const file = new File([blob], 'cropped-photo', {
          type: this.mime,
        })

        // 创建 FormData 对象
        const formData = new FormData()
        formData.append('file', file)

        // 上传裁剪后的图片
        const response = await axios.post(
          uploadConfig.uploadUrl,
          formData,
          {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          }
        )

        // 检查响应
        if (response.data && response.data.code === 0) {
          const uploadedUrl = response.data.data.url

          this.content[this.type].url = uploadedUrl
          this.content[this.type].mime = this.mime
          this.content[this.type].blob = file

          vm.resizeImage(vm.type, vm.mime)
          vm.$emit('closeCropper')
        } else {
          this.$emit('showAlert', 'Cropped image upload failed. Please try again.')
        }
      } catch (error) {
        console.error('Crop upload error:', error)
        this.$emit('showAlert', 'Cropped image upload failed. Please try again.')
      }
    },
  },
  mounted() {
    this.image = this.$refs.image
    this.cropper = new Cropper(this.image, {
      zoomable: false,
      scalable: false,
      // aspectRatio: this.type == 'photo' ? 1 : 16 / 9,
      autoCropArea: 1,
      responsive: true,
      viewMode: 2,
      highlight: false,
      rotatable: true,
    })
  },
}
</script>
